﻿using System;
using System.Collections;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

namespace EXAM.Admin.Page_Admin
{
    public partial class TestTemplate : System.Web.UI.Page
    {
        string sErr = "";
        string _db = "EXA";
        string _cate = "Q0";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BUS.QuestionControl ctr = new BUS.QuestionControl();
                DataTable adt = ctr.GetEnableAll(true, ref sErr);
                Session["drafQst"] = adt;
                DataSet dset = new DataSet("TestLog");
                Session["dsTestLog"] = dset;
                txtID.Text = Session["TestID"].ToString();
                BUS.TestControl testCtr = new BUS.TestControl();
                DTO.TestInfo testInf = testCtr.Get(Convert.ToInt64(txtID.Text), ref sErr);
                lbTitle.Text = testInf.Name;
                hdType.Value = testInf.Type;
                Session["TestID"] = null;
                BUS.Test_LogControl logCtr = new BUS.Test_LogControl();
                int No = logCtr.GetNoTemp(Convert.ToInt64(txtID.Text), testInf.Type);
                txtNo.Text = No.ToString();
                if (!dset.Tables.Contains("dtQuest"))
                {

                    DataTable dtQuest = logCtr.GetLogByNo(No, ref sErr);
                    BUS.Test_Log_AnswerControl ansCtr = new BUS.Test_Log_AnswerControl();
                    DataTable dtAnswer = ansCtr.GetLogByNo(No, ref sErr);
                    dtQuest.TableName = "dtQuest";
                    dtAnswer.TableName = "dtAnswer";
                    dset.Tables.Add(dtQuest.Copy());
                    dset.Tables.Add(dtAnswer.Copy());
                    //DataRelation relat = new DataRelation("reQuest_Ans", new DataColumn[] { dtQuest.Columns["No"], dtQuest.Columns["Line"] }, new DataColumn[] { dtAnswer.Columns["Test_Log_No"], dtAnswer.Columns["Test_Log_Line"] });
                    //dset.Relations.Add(relat);
                }
                BUS.QuestionControl Qctr = new BUS.QuestionControl();
                DataTable dt = Qctr.GetByANALName(_cate, ref sErr);
                dgvANAL.DataSource = dt;
                dgvANAL.DataBind();

            }
            //dgvANAL.RowDataBound+=new GridViewRowEventHandler(dgvANAL_RowDataBound);
            //Win_ViewReport.VisibleOnPageLoad = false;
        }




        protected void dgvQuestion_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            dgvQuestion.DataSource = Session["drafQst"] as DataTable;
        }

        protected void dgvQuestion_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            BUS.QuestionControl ctr = new BUS.QuestionControl();
            string id = "";

            switch (e.CommandName.ToUpper())
            {
                case "SELECTED":

                    id = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"].ToString();
                    DTO.QuestionInfo QuetInf = ctr.Get(Convert.ToInt64(id), ref sErr);
                    AddQuestion(QuetInf);
                    dgvList.Rebind();
                    break;
                case "ADDSELECTED":
                    foreach (GridItem item in dgvQuestion.SelectedItems)
                    {
                        if (item.ItemIndex >= 0 && item is GridDataItem)
                        {
                            id = item.OwnerTableView.DataKeyValues[item.ItemIndex]["ID"].ToString();
                            AddQuestion(ctr.Get(Convert.ToInt64(id), ref sErr));
                        }
                    }
                    dgvList.Rebind();
                    break;
            }
            dgvQuestion.Rebind();
        }

        private void AddQuestion(DTO.QuestionInfo QuetInf)
        {
            BUS.AnswerControl ansCtr = new BUS.AnswerControl();
            DataTable dt = ansCtr.Get_ByIDQuestion(QuetInf.ID, ref sErr);
            DataSet dset = Session["dsTestLog"] as DataSet;
            DTO.Test_LogInfo testLogInf = new DTO.Test_LogInfo();
            DTO.Test_Log_AnswerInfo tmp = new DTO.Test_Log_AnswerInfo();
            if (!dset.Tables.Contains("dtQuest"))
            {
                DataTable dtQuest = testLogInf.ToDataTable();
                dtQuest.Columns.Add("QuestName");
                dtQuest.TableName = "dtQuest";
                DataTable dtAnswer = tmp.ToDataTable();
                dtAnswer.Columns.Add("AnsName");
                dtAnswer.TableName = "dtAnswer";
                dset.Tables.Add(dtQuest);
                dset.Tables.Add(dtAnswer);
                //DataRelation relat = new DataRelation("reQuest_Ans", new DataColumn[] { dtQuest.Columns["No"], dtQuest.Columns["Line"] }, new DataColumn[] { dtAnswer.Columns["Test_Log_No"], dtAnswer.Columns["Test_Log_Line"] });
                //dset.Relations.Add(relat);
            }
            int iNo = -1;
            int iLine = dset.Tables["dtQuest"].Rows.Count + 1;
            if (dset.Tables["dtQuest"].Rows.Count > 0)
            {
                iNo = (int)dset.Tables["dtQuest"].Rows[0]["No"];
            }

            testLogInf.Creation_Time = BUS.CommonControl.ConvertDateToInt(DateTime.Today);
            testLogInf.Line = iLine;
            testLogInf.No = iNo;
            testLogInf.Question_ID = QuetInf.ID;
            testLogInf.User_ID = -1;
            testLogInf.Test_ID = Convert.ToInt64(txtID.Text);
            testLogInf.Type = hdType.Value;
            DataRow newRow = testLogInf.ToDataRow(dset.Tables["dtQuest"]);
            newRow["QuestName"] = QuetInf.Description;
            dset.Tables["dtQuest"].Rows.Add(newRow);
            foreach (DataRow row in dt.Rows)
            {
                tmp = new DTO.Test_Log_AnswerInfo();
                tmp.Answer_ID = Convert.ToInt64(row["ID"]);
                tmp.Test_Log_Line = iLine;
                tmp.Test_Log_No = iNo;
                tmp.Rank = dt.Rows.IndexOf(row);
                DataRow tmpRow = tmp.ToDataRow(dset.Tables["dtAnswer"]);
                tmpRow["AnsName"] = row["Description"];
                tmpRow["Answer_Selected"] = row["IsRight"];
                dset.Tables["dtAnswer"].Rows.Add(tmpRow);
            }
            RebuildDataSet(dset);

            DataTable drafQst = Session["drafQst"] as DataTable;
            DataRow[] arrRow = drafQst.Select("ID=" + QuetInf.ID);
            if (arrRow.Length > 0)
                drafQst.Rows.Remove(arrRow[0]);
            Session["drafQst"] = drafQst;
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Session["TestID"] = null;
            Session["dsTestLog"] = null;
            Response.Redirect("Test.aspx");
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            DataSet ds = Session["dsTestLog"] as DataSet;
            BUS.Test_LogControl logCtr = new BUS.Test_LogControl();
            int maxNo = logCtr.GetMaxNo() + 1;
            if (txtNo.Text != "-1" && txtNo.Text != "0")
            {
                maxNo = Convert.ToInt32(txtNo.Text);
                logCtr.Delete_TestNo(maxNo);
            }
            //if (ds.HasChanges())
            //{
            foreach (DataRow row in ds.Tables["dtQuest"].Rows)
            {
                DTO.Test_LogInfo inf = new DTO.Test_LogInfo(row);
                inf.No = maxNo;
                logCtr.Add(inf, ref sErr);
            }
            BUS.Test_Log_AnswerControl ansCtr = new BUS.Test_Log_AnswerControl();
            foreach (DataRow row in ds.Tables["dtAnswer"].Rows)
            {
                DTO.Test_Log_AnswerInfo ansInf = new DTO.Test_Log_AnswerInfo(row);
                ansInf.Test_Log_No = maxNo;
                ansCtr.Add(ansInf, ref sErr);
            }
            //}
            Session["TestID"] = null;
            Session["dsTestLog"] = null;

            Response.Redirect("Test.aspx");
        }

        protected void dgvList_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            DataSet ds = Session["dsTestLog"] as DataSet;
            dgvList.DataSource = ds;
            //dgvList.MasterTableView.DataSourceID = "dtQuest";
            //dgvList.MasterTableView.DetailTables[0].DataSourceID = "dtAnswer";
        }

        protected void dgvList_ItemCommand(object sender, GridCommandEventArgs e)
        {
            DataSet ds = Session["dsTestLog"] as DataSet;
            if (e.CommandName.ToUpper() == "DELETE")
            {
                DataTable drafQst = Session["drafQst"] as DataTable;

                string line = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Line"].ToString();
                DataRow[] selectRow = ds.Tables["dtQuest"].Select("Line = " + line + "");
                DataRow[] childRow = ds.Tables["dtAnswer"].Select("Test_Log_Line = " + line + "");
                for (int i = childRow.Length - 1; i >= 0; i--)
                    ds.Tables["dtAnswer"].Rows.Remove(childRow[i]);
                for (int i = selectRow.Length - 1; i >= 0; i--)
                {
                    BUS.QuestionControl qstCtr = new BUS.QuestionControl();
                    DTO.QuestionInfo qstInf = qstCtr.Get(Convert.ToInt64(selectRow[i]["Question_ID"]), ref sErr);
                    drafQst.Rows.Add(qstInf.ToDataRow(drafQst));
                    ds.Tables["dtQuest"].Rows.Remove(selectRow[i]);
                }
                Session["drafQst"] = drafQst;
                dgvQuestion.Rebind();

                RebuildDataSet(ds);
                dgvList.Rebind();
            }
            else if (e.CommandName.ToUpper() == "UPDATE")
            {
                GridEditableItem editedItem = e.Item as GridEditableItem;
                //System.Web.UI.UserControl userControl = (System.Web.UI.UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);
                string line = editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["Line"].ToString();

                DataRow[] changedRows = ds.Tables["dtQuest"].Select("Line = " + line);

                if (changedRows.Length != 1)
                {
                    dgvList.Controls.Add(new LiteralControl("Unable to locate the Employee for updating."));
                    e.Canceled = true;
                    return;
                }
                //Set new values
                Hashtable newValues = new Hashtable();
                changedRows[0].BeginEdit();
                e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
                try
                {
                    foreach (DictionaryEntry entry in newValues)
                    {
                        if (ds.Tables["dtQuest"].Columns.Contains(entry.Key.ToString()))
                            changedRows[0][(string)entry.Key] = entry.Value;
                    }
                    changedRows[0].EndEdit();
                    ds.Tables["dtQuest"].AcceptChanges();
                    ds.AcceptChanges();
                    dgvList.Rebind();
                }
                catch (Exception ex)
                {
                    changedRows[0].CancelEdit();

                    Label lblError = new Label();
                    lblError.Text = "Unable to update Question Log. Reason: " + ex.Message;
                    lblError.ForeColor = System.Drawing.Color.Red;
                    dgvList.Controls.Add(lblError);

                    e.Canceled = true;
                }
            }

        }

        private void RebuildDataSet(DataSet ds)
        {
            for (int j = 0; j < ds.Tables["dtQuest"].Rows.Count; j++)
            {
                DataRow row = ds.Tables["dtQuest"].Rows[j];
                string line = row["Line"].ToString();
                DataRow[] childRow = ds.Tables["dtAnswer"].Select("Test_Log_Line = " + line + "");
                for (int i = 0; i < childRow.Length; i++)
                {
                    childRow[i]["Test_Log_Line"] = j + 1;
                }
                row["Line"] = j + 1;
            }
            ds.AcceptChanges();
        }



        protected void btnOK_Click(object sender, EventArgs e)
        {
            string query = "";
            int i = 0;
            foreach (GridViewRow row in dgvANAL.Rows)
            {
                string code = row.Cells[0].Text;
                RadNumericTextBox txtNum1 = (RadNumericTextBox)row.FindControl("txtNum1");
                RadNumericTextBox txtNum2 = (RadNumericTextBox)row.FindControl("txtNum2");
                RadNumericTextBox txtNum3 = (RadNumericTextBox)row.FindControl("txtNum3");

                string value = txtNum1.Value.Value.ToString();
                if (value != "0")
                    query += " Union all SELECT * FROM (Select top " + value + " * from Question where Question.Enabled=1 and ANAL_" + _cate + "=N'" + code + "' AND (Difficulty between " + 1 + " and " + 4 + ") Order by newid()) LV1DATA" + i;

                value = txtNum2.Value.Value.ToString();
                if (value != "0")
                    query += " Union all SELECT * FROM (Select top " + value + " * from Question where Question.Enabled=1 and ANAL_" + _cate + "=N'" + code + "' AND (Difficulty between " + 5 + " and " + 8 + ") Order by newid()) LV2DATA" + i;

                value = txtNum3.Value.Value.ToString();
                if (value != "0")
                    query += " Union all SELECT * FROM (Select top " + value + " * from Question where Question.Enabled=1 and ANAL_" + _cate + "=N'" + code + "' AND (Difficulty between " + 9 + " and " + 10 + ") Order by newid()) LV3DATA" + i;
                i++;
            }
            if (query.Length > 1)
            {
                query = query.Substring(10);
                BUS.CommonControl control = new BUS.CommonControl();
                DataTable dt = control.executeSelectQuery(query);
                foreach (DataRow row in dt.Rows)
                {
                    DTO.QuestionInfo Qinf = new DTO.QuestionInfo(row);
                    AddQuestion(Qinf);
                }
                dgvList.Rebind();
            }
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            foreach (GridItem item in dgvList.SelectedItems)
            {
                if (item.ItemIndex >= 0 && item is GridDataItem)
                {
                    string id = item.OwnerTableView.DataKeyValues[item.ItemIndex]["ID"].ToString();
                    BUS.QuestionControl ctr = new BUS.QuestionControl();
                    AddQuestion(ctr.Get(Convert.ToInt64(id), ref sErr));
                }
            }
            dgvList.Rebind();
        }

        protected void dgvANAL_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row != null && e.Row.DataItem != null)
            {
                DataRowView rowview = e.Row.DataItem as DataRowView;
                RadNumericTextBox txtNum1 = (RadNumericTextBox)e.Row.FindControl("txtNum1");
                RadNumericTextBox txtNum2 = (RadNumericTextBox)e.Row.FindControl("txtNum2");
                RadNumericTextBox txtNum3 = (RadNumericTextBox)e.Row.FindControl("txtNum3");
                string code = rowview["CODE"].ToString();
                BUS.QuestionControl questCtr = new BUS.QuestionControl();
                int countLV1 = questCtr.GetCountANAL_LV(_cate, code, 1, 4, ref sErr);
                int countLV2 = questCtr.GetCountANAL_LV(_cate, code, 5, 8, ref sErr);
                int countLV3 = questCtr.GetCountANAL_LV(_cate, code, 9, 10, ref sErr);
                if (countLV1 == 0)
                    txtNum1.Enabled = false;
                if (countLV2 == 0)
                    txtNum2.Enabled = false;
                if (countLV3 == 0)
                    txtNum3.Enabled = false;
                txtNum1.ToolTip = "Max : " + countLV1;
                txtNum1.MaxValue = countLV1;
                txtNum2.ToolTip = "Max : " + countLV2;
                txtNum2.MaxValue = countLV2;
                txtNum3.ToolTip = "Max : " + countLV3;
                txtNum3.MaxValue = countLV3;
            }
        }





    }
}
